<script lang="ts" setup>
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/store/modules/user"
import { User, Lock, Key, Picture, Loading } from "@element-plus/icons-vue"
import ThemeSwitch from "@/components/ThemeSwitch/index.vue"
import { type FormInstance, FormRules, ElMessage } from "element-plus"
import { checkPw } from "@/utils/validate"
import { restPw } from "@/api/login"
// import { getLoginCodeApi } from "@/api/login"
import { type ILoginRequestData } from "@/api/login/types/login"
// import { aesEncrypt } from "@/utils/encrypt"
const router = useRouter()
const loginFormRef = ref<FormInstance | null>(null)
const baseURL = import.meta.env.VITE_BASE_API

/** 登录按钮 Loading */
const loading = ref(false)
/** 验证码图片 URL */
const codeUrl = ref("")
const key = ref(0)
/** 登录表单数据 */
const loginForm: ILoginRequestData = reactive({
  username: "",
  password: "",
  code: "",
  uuid: ""
})
/** 重置密码表单数据 */
const restForm = reactive<any>({
  username: "",
  password: "",
  NewPassword: "",
  NewPassword1: ""
})

const checkIsPwRepeat = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入密码！"))
  }
  setTimeout(() => {
    if (restForm.NewPassword1 !== restForm.NewPassword) {
      callback(new Error("两次密码不一致！"))
    } else {
      callback()
    }
  }, 100)
}
/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, validator: checkPw, trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
}
/** 重置密码表单校验规则 */
const restFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  NewPassword: [{ required: true, validator: checkPw, trigger: "blur" }],
  NewPassword1: [{ required: true, validator: checkIsPwRepeat, trigger: "blur" }]
}

/** 登录逻辑 */
const handleLogin = () => {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      // console.log(loginForm.code)
      useUserStore()
        .login({
          username: loginForm.username,
          password: loginForm.password,
          code: loginForm.code,
          uuid: loginForm.uuid
        })
        .then(() => {
          router.push({ path: "/" })
        })
        .catch(() => {
          createCode()
          loginForm.password = ""
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}
// console.log(process.env.NODE_ENV)
/** 创建验证码 */
const createCode = () => {
  // 先清空验证码的输入
  loginForm.code = ""
  key.value += 1
  // 获取验证码
  loginForm.uuid = new Date().getTime() + ""
  codeUrl.value = `${baseURL}/getCode?uuid=${loginForm.uuid}`
}

// /** 初始化验证码 */
createCode()
const FLAG = ref<any>(99)
/**重置密码 */
const restFormRef = ref<any>(null)
const dialogVisible = ref<boolean>(false)
const resetForm = () => {
  restFormRef.value.clearValidate()
  restFormRef.value.resetFields()
}
const handleRest = () => {
  dialogVisible.value = true
}
const handleSure = () => {
  restFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      // console.log(loginForm.code)
      restPw({
        username: restForm.username,
        password: restForm.password,
        NewPassword: restForm.NewPassword
      })
        .then((res: any) => {
          console.log(res)
          if (res.code == 200) {
            ElMessage.success(res.data)
            dialogVisible.value = false
          }
        })

        .finally(() => {
          loading.value = false
        })
    } else {
      return false
    }
  })
}
</script>

<template>
  <div class="login-container">
    <ThemeSwitch class="theme-switch" />
    <div class="login-card">
      <div class="title" style="font-size: 18px; font-weight: 500" v-if="FLAG == 1">追创科技</div>
      <div class="title" v-if="FLAG == 99">
        <img src="@/assets/layout/logo-text-2.png" />
      </div>
      <div class="content">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input
              v-model.trim="loginForm.username"
              placeholder="用户名"
              type="text"
              tabindex="1"
              :prefix-icon="User"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model.trim="loginForm.password"
              placeholder="密码"
              minlength="8"
              maxlength="16"
              type="password"
              tabindex="2"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model.trim="loginForm.code"
              placeholder="验证码"
              type="text"
              tabindex="3"
              :prefix-icon="Key"
              maxlength="7"
              size="large"
            >
              <template #append>
                <el-image :src="codeUrl" @click="createCode" draggable="false" :key="key">
                  <template #placeholder>
                    <el-icon><Picture /></el-icon>
                  </template>
                  <template #error>
                    <el-icon><Loading /></el-icon>
                  </template>
                </el-image>
              </template>
            </el-input>
          </el-form-item>
          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleLogin"> 登 录 </el-button>
          <p style="text-align: center">
            <el-link :loading="loading" type="primary" @click.prevent="handleRest"> 重置密码 </el-link>
          </p>
        </el-form>
      </div>
    </div>
    <div class="footer">
      <el-link href="https://beian.miit.gov.cn/">浙ICP备2023050079号-2</el-link>
    </div>
    <el-dialog v-model="dialogVisible" title="重置密码" @close="resetForm" width="30%">
      <el-form ref="restFormRef" :model="restForm" :rules="restFormRules">
        <el-form-item prop="username">
          <el-input
            v-model.trim="restForm.username"
            placeholder="用户名"
            type="text"
            tabindex="1"
            :prefix-icon="User"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model.trim="restForm.password"
            placeholder="原密码"
            type="password"
            tabindex="2"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="NewPassword">
          <el-input
            minlength="8"
            maxlength="16"
            v-model.trim="restForm.NewPassword"
            placeholder="新密码"
            type="password"
            tabindex="3"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="NewPassword1">
          <el-input
            v-model.trim="restForm.NewPassword1"
            placeholder="确认新密码"
            type="password"
            tabindex="4"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-button :loading="loading" type="primary" size="large" @click.prevent="handleSure"> 确定 </el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100%;
  .footer {
    position: fixed;
    bottom: 10px;
    padding: 20px;
    line-height: 30px;
    text-align: center;
  }
  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }
  .login-card {
    width: 480px;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: #fff;
    overflow: hidden;
    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 150px;
      img {
        height: 80%;
      }
    }
    .content {
      padding: 20px 50px 50px 50px;
      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;
        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }
      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}
.el-form-item {
  margin-bottom: 30px !important;
}
</style>
